﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace GT.Framework.RabbitMQ.Core
{
    public class DoRabbitMQBase : IDisposable
    {
        public static IConnection Connection { get; private set; }

        public static IModel Channel { get; private set; }

        private bool _disposed = false;
        static DoRabbitMQBase()
        {
            Connection = RabbitMQManager.GetClient();
            Channel = Connection.CreateModel();
        }


        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    // 释放链接
                    Connection.Dispose();
                    Channel.Dispose();
                    Connection = null;
                    Channel = null;
                }
            }
            this._disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        static void UnInitialize()
        {
            Channel.Close();
            Connection.Close();
        }

        public static byte[] Serialize(object obj)
        {
            using (var stream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);
                return stream.ToArray();
            }
        }
    }
}
